package com.ssrs.platform.bl;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ssrs.framework.util.SpringUtil;
import com.ssrs.framework.web.config.ThreadPoolConfigProperties;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author ssrs
 * Date: Created in 2020/7/25 13:43
 * Description: 日志插入线程池
 */
public class LogTheadPool {
    private static final Log log = LogFactory.get(LogTheadPool.class);
    private static Object mutex = new Object();
    private static LogTheadPool instance;
    private ThreadPoolExecutor threadPool;


    private LogTheadPool() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNamePrefix("eightroes-log-").build();
        ThreadPoolConfigProperties poolConfigProperties = SpringUtil.getBean(ThreadPoolConfigProperties.class);
        int corePoolSize = poolConfigProperties.getCorePoolSize();
        int maxPoolSize = poolConfigProperties.getMaxPoolSize();
        int keepAliveSeconds = poolConfigProperties.getKeepAliveSeconds();
        this.threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveSeconds, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
        log.info("日志线程池-核心线程数定义为[" + corePoolSize + "], 最大支持的线程数量为[" + maxPoolSize + "], 线程池维护线程所允许的空闲时间[" + keepAliveSeconds + "].");
    }

    public static LogTheadPool getInstance() {
        synchronized (mutex) {
            if (instance == null) {
                synchronized (mutex) {
                    if (instance == null) {
                        instance = new LogTheadPool();
                    }
                }
            }
        }
        return instance;
    }

    public synchronized void addTask(Runnable task) {
        this.threadPool.execute(task);

    }

    public int getActiveCount() {
        return this.threadPool.getActiveCount();
    }

    public int getQueueSize() {
        return this.threadPool.getQueue().size();
    }
}
